package drds.binlog.parse.mysql;

import com.lmax.disruptor.LifecycleAware;
import com.lmax.disruptor.WorkHandler;
import drds.binlog.binlog_event.LogEvent;
import drds.binlog.binlog_event.event.rows_log_event.RowsLogEvent;
import drds.binlog.common.Authors;
import drds.binlog.data_object.Entry;
import drds.binlog.parse.exception.ParseException;
import drds.common.Author;

@Author(name = Authors.LI_YANG)
class DmlParserStage implements WorkHandler<MessageEvent>, LifecycleAware
{

    private MultiStageCoprocessor multiStageCoprocessor;

    public DmlParserStage(MultiStageCoprocessor multiStageCoprocessor)
    {
        this.multiStageCoprocessor = multiStageCoprocessor;
    }

    @Override
    public void onEvent(MessageEvent messageEvent) throws Exception
    {
        try
        {
            if (messageEvent.isNeedDmlParse())
            {
                int logType = messageEvent.getLogEvent().getLogHeader().getLogType();
                Entry entry = null;
                switch (logType)
                {
                    case LogEvent.rows_query_log_event:
                        entry = multiStageCoprocessor.binlogLogEventConverter.parse(messageEvent.getLogEvent(), false);
                        break;
                    default:
                        // 单独解析dml事件
                        entry = multiStageCoprocessor.binlogLogEventConverter.parseRowsEvent((RowsLogEvent) messageEvent.getLogEvent(), messageEvent.getTableMetaData());
                }

                messageEvent.setEntry(entry);
            }
        } catch (Throwable e)
        {
            multiStageCoprocessor.parseException = new ParseException(e);
            throw multiStageCoprocessor.parseException;
        }
    }

    @Override
    public void onStart()
    {

    }

    @Override
    public void onShutdown()
    {

    }
}
